/*
 * PlayListPanel.java
 *
 * Created on June 15, 2005, 10:06 PM
 */
package com.bff.mpd.musicjukebox.ui;

import com.bff.bjj.ui.component.MusicList;
import com.bff.bjj.ui.component.BJJPanel;
import com.bff.bjj.ui.component.BJJButton;
import com.bff.mpd.utils.Utils;
import com.bff.mpd.musicjukebox.lib.JukeboxProperties;
import com.bff.mpd.musicjukebox.ui.components.PlaylistCellRenderer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import org.bff.javampd.MPDDatabase;
import org.bff.javampd.MPDPlaylist;
import org.bff.javampd.exception.MPDConnectionException;
import org.bff.javampd.exception.MPDDatabaseException;
import org.bff.javampd.exception.MPDPlaylistException;
import org.bff.javampd.objects.MPDSong;

/**
 *
 * @author  Bill
 */
public class SavedPlaylistPanel extends BJJPanel {

    private MPDPlaylist playlist;
    private MPDDatabase database;
    private DefaultComboBoxModel playlistModel;
    private DefaultListModel playlistSongsModel;

    /** Creates new form PlayListPanel */
    public SavedPlaylistPanel() {
        setPlaylist(JukeboxProperties.getInstance().getPlaylist());
        setDatabase(JukeboxProperties.getInstance().getDatabase());

        playlistModel = new DefaultComboBoxModel();
        playlistSongsModel = new DefaultListModel();

        initComponents();

        cbPlaylists.setSelectedIndex(-1);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        playListButtonPanel = new BJJPanel();
        btnDelete = new BJJButton();
        btnLoad = new BJJButton();
        btnRefresh = new BJJButton();
        btnReplace = new BJJButton();
        btnGeneratePlaylist = new BJJButton();
        jPanel3 = new BJJPanel();
        jScrollPane = new javax.swing.JScrollPane();
        listPlaylist = new MusicList();
        jPanel1 = new BJJPanel();
        cbPlaylists = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(258, 500));
        setLayout(new java.awt.BorderLayout());

        playListButtonPanel.setLayout(new java.awt.GridBagLayout());

        btnDelete.setText("Delete");
        btnDelete.setMaximumSize(new java.awt.Dimension(99, 25));
        btnDelete.setMinimumSize(new java.awt.Dimension(99, 25));
        btnDelete.setPreferredSize(new java.awt.Dimension(99, 25));
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        playListButtonPanel.add(btnDelete, gridBagConstraints);

        btnLoad.setText("Load");
        btnLoad.setMaximumSize(new java.awt.Dimension(99, 25));
        btnLoad.setMinimumSize(new java.awt.Dimension(99, 25));
        btnLoad.setPreferredSize(new java.awt.Dimension(99, 25));
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        playListButtonPanel.add(btnLoad, gridBagConstraints);

        btnRefresh.setText("Refresh");
        btnRefresh.setMaximumSize(new java.awt.Dimension(99, 25));
        btnRefresh.setMinimumSize(new java.awt.Dimension(99, 25));
        btnRefresh.setPreferredSize(new java.awt.Dimension(99, 25));
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        playListButtonPanel.add(btnRefresh, gridBagConstraints);

        btnReplace.setText("Replace");
        btnReplace.setMaximumSize(new java.awt.Dimension(99, 25));
        btnReplace.setMinimumSize(new java.awt.Dimension(99, 25));
        btnReplace.setPreferredSize(new java.awt.Dimension(99, 25));
        btnReplace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnReplaceActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        playListButtonPanel.add(btnReplace, gridBagConstraints);

        btnGeneratePlaylist.setText("Random Playlist");
        btnGeneratePlaylist.setActionCommand("Generate");
        btnGeneratePlaylist.setPreferredSize(new java.awt.Dimension(170, 25));
        btnGeneratePlaylist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGeneratePlaylistActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 6);
        playListButtonPanel.add(btnGeneratePlaylist, gridBagConstraints);

        add(playListButtonPanel, java.awt.BorderLayout.SOUTH);

        jPanel3.setLayout(new java.awt.BorderLayout());

        listPlaylists();
        listPlaylist.setModel(playlistSongsModel);
        listPlaylist.setCellRenderer(new PlaylistCellRenderer());
        listPlaylist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listPlaylistMouseClicked(evt);
            }
        });
        jScrollPane.setViewportView(listPlaylist);

        jPanel3.add(jScrollPane, java.awt.BorderLayout.CENTER);

        cbPlaylists.setModel(playlistModel);
        cbPlaylists.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbPlaylistsActionPerformed(evt);
            }
        });
        jPanel1.add(cbPlaylists);

        jPanel3.add(jPanel1, java.awt.BorderLayout.NORTH);

        add(jPanel3, java.awt.BorderLayout.CENTER);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Saved Playlists");
        add(jLabel1, java.awt.BorderLayout.NORTH);
    }// </editor-fold>//GEN-END:initComponents

    private void listPlaylistMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listPlaylistMouseClicked
    }//GEN-LAST:event_listPlaylistMouseClicked

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        String pl = getSelectedPlaylist();
        int n = JOptionPane.showConfirmDialog(this,
                "Are you sure you want to delete " + pl + "?",
                "Are You Sure?",
                JOptionPane.YES_NO_OPTION);

        if (n == JOptionPane.YES_OPTION) {
            try {
                setCursor(Utils.getHourglassCursor());
                try {
                    getPlaylist().deletePlaylist(pl);
                } catch (MPDConnectionException ex) {
                    Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (MPDPlaylistException ex) {
                    Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
                }
                cbPlaylists.removeItem(pl);
            } finally {
                setCursor(Utils.getNormalCursor());
            }
        }
}//GEN-LAST:event_btnDeleteActionPerformed

private void cbPlaylistsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbPlaylistsActionPerformed
    listSongs();
}//GEN-LAST:event_cbPlaylistsActionPerformed

private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
    refresh();
}//GEN-LAST:event_btnRefreshActionPerformed

private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
    String pl = getSelectedPlaylist();

    try {
        setCursor(Utils.getHourglassCursor());
        for (MPDSong song : getDatabase().listPlaylistSongs(pl)) {
            try {
                getPlaylist().addSong(song);
            } catch (MPDConnectionException ex) {
                Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MPDPlaylistException ex) {
                Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (MPDConnectionException ex) {
        Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MPDDatabaseException ex) {
        Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        setCursor(Utils.getNormalCursor());
    }
}//GEN-LAST:event_btnLoadActionPerformed

private void btnReplaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReplaceActionPerformed
    String pl = getSelectedPlaylist();

    try {
        setCursor(Utils.getHourglassCursor());
        try {
            getPlaylist().clearPlaylist();
        } catch (MPDConnectionException ex) {
            Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MPDPlaylistException ex) {
            Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        for (MPDSong song : getDatabase().listPlaylistSongs(pl)) {
            try {
                getPlaylist().addSong(song);
            } catch (MPDConnectionException ex) {
                Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MPDPlaylistException ex) {
                Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (MPDConnectionException ex) {
        Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MPDDatabaseException ex) {
        Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        setCursor(Utils.getNormalCursor());
    }
}//GEN-LAST:event_btnReplaceActionPerformed

private void btnGeneratePlaylistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGeneratePlaylistActionPerformed
    new RandomPlaylistFrame().setVisible(true);
}//GEN-LAST:event_btnGeneratePlaylistActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnGeneratePlaylist;
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnReplace;
    private javax.swing.JComboBox cbPlaylists;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JList listPlaylist;
    private javax.swing.JPanel playListButtonPanel;
    // End of variables declaration//GEN-END:variables

    private void listPlaylists() {
        playlistModel.removeAllElements();
        try {
            for (String pl : getDatabase().listPlaylists()) {
                playlistModel.addElement(pl);
            }
        } catch (MPDConnectionException ex) {
            Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MPDDatabaseException ex) {
            Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void listSongs() {
        if (cbPlaylists.getSelectedIndex() > -1) {
            final SplashScreen sp = new SplashScreen(Utils.getParentComponent(this));
            sp.setIndeterminate(true);
            sp.setTitleLabel("Loading");
            sp.setMainTextArea("\nLoading song list.\n\n");
            sp.setProgressBarLabel("Loading...");
            sp.pack();

            playlistSongsModel = new DefaultListModel();

            new Thread(new Runnable() {

                @Override
                public void run() {
                    if (cbPlaylists.getSelectedItem() != null) {
                        try {
                            List<MPDSong> songs = new ArrayList<MPDSong>(getDatabase().listPlaylistSongs((String) cbPlaylists.getSelectedItem()));
                            for (MPDSong song : songs) {
                                playlistSongsModel.addElement(song);
                            }
                            listPlaylist.setModel(playlistSongsModel);
                        } catch (MPDConnectionException ex) {
                            Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (MPDDatabaseException ex) {
                            Logger.getLogger(SavedPlaylistPanel.class.getName()).log(Level.SEVERE, null, ex);
                        } finally {
                            sp.setStopped(true);
                        }
                    }
                }
            }).start();
        }
    }

    public void refresh() {
        new Thread(new Runnable() {

            public void run() {
                listPlaylists();
            }
        }).start();
    }

    /**
     * @return the playlist
     */
    public MPDPlaylist getPlaylist() {
        return playlist;
    }

    /**
     * @param playlist the playlist to set
     */
    public void setPlaylist(MPDPlaylist playlist) {
        this.playlist = playlist;
    }

    /**
     * @return the database
     */
    public MPDDatabase getDatabase() {
        return database;
    }

    /**
     * @param database the database to set
     */
    public void setDatabase(MPDDatabase database) {
        this.database = database;
    }

    private String getSelectedPlaylist() {
        return (String) cbPlaylists.getSelectedItem();
    }
}
